package com.ys.controller.api.storage;

import com.ys.config.MenuId;
import com.ys.entity.storage.TccStockAllocate;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccStockAllocateService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 库存调拨单
 */
@Controller
@RequestMapping("/api/inter/tccStockAllocateNoManage")
public class ApiInterTccStockAllocateNoManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccStockAllocateNoManageController.class);

    @Autowired
    private CommonApiService<TccStockAllocate> commonApiService;


    //菜单id
    private Long menuId = MenuId.TCC_StockAllocate_NoManage;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccStockAllocateNoManage:view";
    private final String PERMISSIONS_ADD = "tccStockAllocateNoManage:add";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccStockAllocate setSeachSql(TccStockAllocate cond){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm")
                .addField("C.Vgsjc AS vgsjc")//运营公司简称

                //子件信息
                .addLeftJoin("TCC_StockAllocateItem SA ON SA.Pbid = A.Bid")
                .addField("SA.StockControlIdByOld AS stockControlIdByOld")//旧库存id
                .addField("SA.StockControlIdByNew AS stockControlIdByNew")//新库存id
                .addField("SA.SubCode AS subCode")//子件编码
                .addField("SA.ProductNum AS productNum")//库存可用数量（旧）
                .addField("SA.ProductNumAll AS productNumAll")//库存总数量（旧）
                .addField("SA.AllocateNum AS allocateNum")//调拨数量
                .addField("SA.Chw AS chw")//货位编码
                .addField("SA.CompanyVid AS companyVid")//所属公司VID
                .addField("SA.VgsbmByOld AS vgsbmByOld")//运营公司编码
                .addField("SA.VgsShByOld AS vgsShByOld")//公司税号（旧）
                .addField("SA.RkBid AS rkBid")//商品组装单号
                .addField("FORMAT(SA.DrksjByOld, 'yyyy-MM-dd HH:mm:ss') AS drksjByOld")//入库时间（旧）
                .addField("FORMAT(SA.DrksjByNew, 'yyyy-MM-dd HH:mm:ss') AS drksjByNew")//入库时间（新）

                .addLeftJoin("TP_ProductBasisComponent SB ON SB.Code = SA.SubCode")//listing库子件信息
                .addField("SB.Name AS subName")//子件名称
                .addField("SB.SubCodeMerge AS subCodeMerge")//子件合并编码

                .addLeftJoin("TCC_Location SD ON SD.Chw = SA.Chw")//货位信息表
                .addField("SD.Vhw AS vhw")//货位
                .addLeftJoin("TCC_WarehouseArea SE ON SE.Ckq = SD.Ckq")//库区
                .addField("SE.Vkq AS vkq")//库区
                .addLeftJoin("TCC_Warehouse SF ON SF.Cck = SE.Cck")//仓库
                .addField("SF.Vck AS vck")//仓库

                .addLeftJoin("THR_OperateCompanyApply SG ON SG.Vgsbm = SA.VgsbmByOld")
                .addField("SG.Vgsjc AS vgsjcByOld")//运营公司简称

                .addLeftJoin("TB_CompanyInfo SH ON SH.VId = SA.CompanyVid")
                .addField("SH.Vname AS vname")//公司名称

                .addField("DATEDIFF(day, SA.DrksjByNew, getdate()) kcdays")//库存天数

                .setIsManage(0)

                //排序

        .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccStockAllocate cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccStockAllocate cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccStockAllocate> util = new ExportExcelUtils<>(new TccStockAllocate());
            String toFilePath = util.exportExcel(listData, listField, "库存调拨单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


}